var wineApp = wineApp || {};
wineApp.myorder = (function() {
    var key = wineApp.CONFIG.STORAGE.PREFIX + '.' + 'userInfo.msg';
    var userInfo = wineApp.localStorage.get(key);
    var pageSize = 10;
    var resourceURL = wineApp.tool.getResourceURL();
    var paramType = $.url().param()['type'];
    var orderType = wineApp.CONFIG.ORDER_STATUS[paramType];
    var template =
        '<div orderId=#orderId# class="wine_order_list">' +
        '<h2><span><i>#payType#</i></span>订单编号：#orderNo#</h2>' +
        '#plandetail#' +
        '<div class="wine_statistics"><span>合计：<b>#amount#元</b></span>共计<b>#count#</b>件商品</div>' +
        '<div class="wine_statistics"><span>#orderTime#</b></span>订单时间</div>' +
        '#operataion#' +
        '</div>'
    var plandetiltemplate =
        '<li>' +
        '<dl>' +
        '<dt>' +
        '<a href="#wineDetail#"><img src="#wineImg#" /></a>' +
        '</dt>' +
        '<dd><a href="#wineDetail#">#wineName#' +
        '<p><b>￥#priceIn#</b>/<span>#priceOut#</span></p>' +
        '<p class="wine_order_time">#num#箱</p></a></dd>' +
        '</dl>' +
        '</li>';
    if (paramType == null) {
        paramType = 'all';
    }
    var operation = {};
    var initPage = function() {
        initOperation();
        orderList(paramType);
        //initScroll();
        initEvent();
        wineApp.common.initBanner();
    }

    var initEvent = function() {
        $(document).on('click', '.pay', function(event) {
            event.preventDefault();
            var orderNo = $(this).attr('order');
            wineApp.orderutil.loadOrderInfoWithOrderId(orderNo).then(function(orderInfo) {
                var data = {
                    orderid: orderInfo.orderid,
                    sum: orderInfo.sum
                }
                layer.open({
                    content: '请选择支付方式',
                    btn: ['支付宝', '微信支付'],
                    skin: 'footer',
                    yes: function(index) {
                        wineApp.orderutil.alipayment(data);
                        layer.close(index);
                    },
                    no: function() {
                        wineApp.orderutil.wechatPayment(data);
                    }

                });
            })

        }).on('click', '.delete', function(event) {
            event.preventDefault();
            var orderId = $(this).attr('order');
            var $this = $(this);
            var ajaxUrl = wineApp.CONFIG.API.orderdelete;
            wineApp.ajax.post(ajaxUrl, {
                orderid: orderId
            }).done(function(data) {
                //window.loction.href = "order_list.html";
                $this.parent().parent().remove()

            })
        }).on('click', '.wine_order_list', function(event) {
            //event.preventDefault();
            //var orderId = $(this).attr('orderId');
            //window.location.href = 'order.html?orderId='+orderId;
        });
    }
    var initOperation = function() {
        var waitPay = '<div class="wine_order_btn">' +
            '<a href="javascript:void(0)" class="delete" order="#orderNo#">删除订单</a>' +
            '<a href="javascript:void(0)" class="cancel" order="#orderNo#">取消订单</a>' +
            '<a href="javascript:void(0)" class="pay" order="#orderNo#" class="wine_order_confirm">立即付款</a></div>';

        var complete = '<div class="wine_order_btn">' +
            '<a href="javascript:void(0)" order="#orderNo#">删除订单</a>' +
            //'<a href="#">查看物流</a>' +
            '<a href="javascript:void(0)" order="#orderNo#" class="wine_order_confirm">评价订单</a>' +
            '</div>';

        var waitRecv = '<div class="wine_order_btn"><a href="javascript:void(0)">延长收货</a><a href="">查看物流</a><a href="javascript:void(0)" class="wine_order_confirm" order="#orderNo#">确认收货</a></div>';
        //var closed = '<div class="wine_order_btn"><a href="">删除订单</a></div>';
        operation = {
            "WAIT_PAY": waitPay,
            "WAIT_SEND": "",
            "WAIT_RECV": waitRecv,
            "COMPLETE": "",
            "待付款": waitPay,
            "待发货": "",
            "已发货": waitRecv,
            "交易完成": complete,
            "已评价": "",
            "交易取消": "",
        }

    }
    var initScroll = function() {
        $('#scroll').infinitescroll({
            dataType: 'json',
            appendCallback: false,
            nextSelector: '#page2',
            state: {
                currPage: 0
            },
            pixelsFromNavToBottom: 10,

            debug: true,
            path: function(currPage) {
                var offset = currPage * pageSize;

                var ajaxUrl = wineApp.tool.getBaseApiURL() + wineApp.CONFIG.API.accountorder + '?userId=' + userInfo.platUser.id + '&offset=' + offset + '&fetchSize=' + pageSize;
                if (paramType != 'all') {
                    ajaxUrl += '&type=' + orderType;
                }
                return ajaxUrl;
            }
        }, function(data, opts) {
            var isDone = false;
            var currPage = opts.state.currPage;
            console.log('currpage2:' + currPage);
            if (isDone) {
                $('#scroll').infinitescroll('update', {
                    state: {
                        currPage: currPage - 1
                    }
                })
            }

            if (opts.state.currPage * pageSize <= data.msg.total) {
                bindData(data);
                isDone = false;
            } else {
                isDone = true;
                console.log('complete')
            }

        })
    }
    var orderList = function(type) {

        var ajaxUrl = wineApp.CONFIG.API.myorders;
        wineApp.ajax.post(ajaxUrl, {}).done(bindData);
    }

    var bindData = function(data) {
        if (data.list.length > 0) {
            $('#notfound').remove();
        }
        $.each(data.list, function(index, order) {
            var param = {};
            var tmp = template;
            var details = order.details;

            param.payType = order.statmsg;
            param.orderId = order.id;
            param.orderTime = order.otime;
            param.orderNo = order.orderid;
            param.count = details.length;
            param.amount = order.sum;

            param.plandetail = renderPlandetail(details);
            if (paramType == 'all') {
                tmp = tmp.replace('#operataion#', operation[order.statmsg]);
            } else {
                var op = operation[paramType] == null ? "" : operation[paramType];
                tmp = tmp.replace('#operataion#', op);
            }
            for (var prop in param) {
                var reg = new RegExp('#' + prop + '#', 'gm');
                tmp = tmp.replace(reg, param[prop]);
            }
            $('.wine_mywine').append(tmp);
        });
    }
    var renderPlandetail = function(details) {
        var result = ''
        $.each(details, function(index, detail) {
            var tmp = plandetiltemplate;
            var param = {};
            param.wineName = detail.proname;
            param.wineDetail = "wine_detail.html?wineId=" + detail.prodid;
            param.wineImg = resourceURL + '/' + detail.titleimg;
            param.priceIn = detail.price;
            param.priceOut = detail.oprice;
            param.num = detail.num;
            for (var prop in param) {
                var reg = new RegExp('#' + prop + '#', 'gm');
                tmp = tmp.replace(reg, param[prop]);
            }
            result += tmp;
        });
        return '<ul>' + result + '</ul>';
    }
    return {
        initPage: initPage
    }
})();

$(document).ready(function() {
    //$('.wine_footer').remove();
    wineApp.common.initHeaderIcon(0, true, {
        camera: false,
        search: false
    });
    wineApp.myorder.initPage();
    //wineApp.common.initTabs('#tabs');
});